package com.yy.job.common.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.base.Preconditions;
import com.yy.job.common.dao.YYJobStepDOMapper;
import com.yy.job.common.dao.po.YYJobStepDO;
import com.yy.job.common.dao.po.YYJobStepDOExample;
import com.yy.job.common.service.IBaseService;

@Service
public class YYJobStepServiceImpl implements IBaseService<YYJobStepDO> {

	@Autowired
	private YYJobStepDOMapper queueJobTaskDOMapper;

	@Override
	public Long saveSelective(YYJobStepDO jobTaskDO) {
		Date nowDate = new Date();
		if (jobTaskDO.getId() == null) {
			if (jobTaskDO.getGmtCreated() == null) {
				jobTaskDO.setGmtCreated(nowDate);
			}
			if (jobTaskDO.getGmtModified() == null) {
				jobTaskDO.setGmtModified(nowDate);
			}
			if (StringUtils.isEmpty(jobTaskDO.getIsDeleted())) {
				jobTaskDO.setIsDeleted("N");
			}
			this.queueJobTaskDOMapper.insert(jobTaskDO);
			return jobTaskDO.getId();
		} else {
			if (jobTaskDO.getGmtModified() == null) {
				jobTaskDO.setGmtModified(nowDate);
			}
			this.queueJobTaskDOMapper.updateByPrimaryKeySelective(jobTaskDO);
			return jobTaskDO.getId();
		}
	}

	/**
	 * 修改状态
	 * 
	 * @param id
	 * @param newStatus
	 * @param modifier
	 */
	public void updateStatusById(Long id, String status, String modifier) {
		Preconditions.checkArgument(id != null, "id is null");
		Preconditions.checkArgument(StringUtils.isNotEmpty(status), "status is null");
		Preconditions.checkArgument(StringUtils.isNotEmpty(modifier), "modifier is null");
		
		YYJobStepDO jobTaskDO = new YYJobStepDO();
		jobTaskDO.setId(id);
		jobTaskDO.setStepStatus(status);
		jobTaskDO.setModifier(modifier);
		jobTaskDO.setGmtModified(new Date());

		this.saveSelective(jobTaskDO);
	}

	/**
	 * 查询步骤列表
	 * 
	 * @param jobId
	 * @return
	 */
	public List<YYJobStepDO> selectStepsByJobId(Long jobId) {
		Preconditions.checkArgument(jobId != null, "jobId can not be null");
		YYJobStepDOExample example = new YYJobStepDOExample();
		example.createCriteria().andJobIdEqualTo(jobId).andIsDeletedEqualTo("N");

		return this.queueJobTaskDOMapper.selectByExample(example);
	}

}
